package com.cskaoyan.wordmemorize.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLog;
import com.cskaoyan.wordmemorize.common.aspect.operate.OperateLogConstant;
import com.cskaoyan.wordmemorize.converter.AIReadConverter;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationDO;
import com.cskaoyan.wordmemorize.dao.entity.UserVocAISituationOptionDO;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationMapper;
import com.cskaoyan.wordmemorize.dao.mapper.UserVocAISituationOptionMapper;
import com.cskaoyan.wordmemorize.dto.admin.PageDTO;
import com.cskaoyan.wordmemorize.dto.admin.UserVocAISituationDTO;
import com.cskaoyan.wordmemorize.request.PageRequest;
import com.cskaoyan.wordmemorize.request.UserVocAISituationCommand;
import com.cskaoyan.wordmemorize.request.UserVocAISituationOptionCommand;
import com.cskaoyan.wordmemorize.service.AIReadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AIReadServiceImpl implements AIReadService {

    @Autowired
    UserVocAISituationMapper userVocAISituationMapper;
    @Autowired
    UserVocAISituationOptionMapper userVocAISituationOptionMapper;
    @Autowired
    AIReadConverter aiReadConverter;

    /*
            添加AI阅读场景以及选项信息(后台等级特权管理-AI阅读)
    */
    @Override
    @OperateLog(dataType = "AI阅读", operateType = OperateLogConstant.OPERATE_ADD)
    public void addAISituation(UserVocAISituationCommand command) {
        UserVocAISituationDO situationDO = new UserVocAISituationDO();
        situationDO.setName(command.getName());
        situationDO.setStatus(command.getStatus());
        situationDO.setDescription(command.getDescription());

        int effectedRow = userVocAISituationMapper.insert(situationDO);

        System.out.println("受影响行数：" + effectedRow);
        if (command.getOptions() != null && !command.getOptions().isEmpty()){
            for (UserVocAISituationOptionCommand optionCommand : command.getOptions()){
                UserVocAISituationOptionDO optionDO = new UserVocAISituationOptionDO();
                optionDO.setSituationId(situationDO.getId());  // 使用新生成的情景id
                optionDO.setName(optionCommand.getName());
                optionDO.setDescription(optionCommand.getDescription());

                int optionRow = userVocAISituationOptionMapper.insert(optionDO);
                System.out.println("选项受影响行数：" + optionRow);
            }
        }
    }

    /*
        更新AI阅读场景以及选项信息(后台等级特权管理-AI阅读)
     */
    @Override
    @OperateLog(dataType = "AI阅读", operateType = OperateLogConstant.OPERATE_UPDATE)
    public void updateAISituation(UserVocAISituationCommand command) {
        LambdaUpdateWrapper<UserVocAISituationDO> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserVocAISituationDO::getId,command.getId())
                .set(UserVocAISituationDO::getName,command.getName())
                .set(UserVocAISituationDO::getStatus,command.getStatus())
                .set(UserVocAISituationDO::getDescription,command.getDescription());

        userVocAISituationMapper.update(null,updateWrapper);

        if(command.getOptions() != null){
            LambdaQueryWrapper<UserVocAISituationOptionDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserVocAISituationOptionDO::getSituationId,command.getId());
            List<UserVocAISituationOptionDO> existingOptions = userVocAISituationOptionMapper.selectList(queryWrapper);

            for (UserVocAISituationOptionCommand optionCommand : command.getOptions()){
                if(optionCommand.getId() == null){
                    // 新增选项
                    UserVocAISituationOptionDO newOption = new UserVocAISituationOptionDO();
                    newOption.setSituationId(Long.parseLong(command.getId()));
                    newOption.setName(optionCommand.getName());
                    newOption.setDescription(newOption.getDescription());
                    userVocAISituationOptionMapper.insert(newOption);
                }else{
                    LambdaUpdateWrapper<UserVocAISituationOptionDO> optionUpdateWrapper = new LambdaUpdateWrapper<>();
                    optionUpdateWrapper.eq(UserVocAISituationOptionDO::getId,optionCommand.getId())
                            .set(UserVocAISituationOptionDO::getName,optionCommand.getName())
                            .set(UserVocAISituationOptionDO::getDescription,optionCommand.getDescription());
                    userVocAISituationOptionMapper.update(null,optionUpdateWrapper);

                    existingOptions.removeIf(opt -> opt.getId().equals(optionCommand.getId()));

                }
            }

            for (UserVocAISituationOptionDO toDelete : existingOptions){
                userVocAISituationOptionMapper.deleteById(toDelete.getId());
            }
        }
    }

    /*
        删除AI阅读场景(后台等级特权管理-AI阅读)
     */
    @Override
    @OperateLog(dataType = "AI阅读", operateType = OperateLogConstant.OPERATE_SINGLE_DELETE)
    public void deleteAISituation(Long id) {
        int effectedRow = userVocAISituationMapper.deleteById(id);
        System.out.println("受影响行数：" + effectedRow);

    }

    /*
         删除AI阅读场景中的某个选项(后台等级特权管理-AI阅读)
      */
    @Override
    @OperateLog(dataType = "AI阅读", operateType = OperateLogConstant.OPERATE_SINGLE_DELETE)
    public void deleteAISituationOption(Long id) {
        int effectedRow = userVocAISituationOptionMapper.deleteById(id);
        System.out.println("受影响行数：" + effectedRow);

    }

    /*
       批量删除AI阅读场景(后台等级特权管理-AI阅读)
    */
    @Override
    @OperateLog(dataType = "AI阅读", operateType = OperateLogConstant.OPERATE_BATCH_DELETE)
    public void batchDeleteAISituationOption(List<Long> ids) {
        int effectedRow = userVocAISituationMapper.deleteBatchIds(ids);
        System.out.println("受影响行数： " + effectedRow);
    }

    /*
      分页查询AI阅读场景信息(后台等级特权管理-AI阅读)
    */
    @Override
    public PageDTO<UserVocAISituationDTO> getAISituationList(PageRequest pageRequest) {
        // 如果查询页数为空（不是分页查询）,全表查询
        if(pageRequest.getPageNum() == null){
            List<UserVocAISituationDO> userVocAISituationDOS = userVocAISituationMapper.selectList(null);

            userVocAISituationDOS.forEach(situation -> {
                LambdaQueryWrapper<UserVocAISituationOptionDO> optionWrapper = new LambdaQueryWrapper<>();
                optionWrapper.eq(UserVocAISituationOptionDO::getSituationId,situation.getId());
                List<UserVocAISituationOptionDO> options = userVocAISituationOptionMapper.selectList(optionWrapper);
                situation.setOptions(options);
            });

            return aiReadConverter.toUserVocAISituationPage(userVocAISituationDOS,(long)userVocAISituationDOS.size());
        }

        Page<UserVocAISituationDO> pageParam = new Page<>(pageRequest.getPageNum(),pageRequest.getCount());
        LambdaQueryWrapper<UserVocAISituationDO> userSituationWrapper = new LambdaQueryWrapper<>();
        if(pageRequest.getKeyword() != null){
            userSituationWrapper.like(UserVocAISituationDO::getName,pageRequest.getKeyword());
        }
        Page<UserVocAISituationDO> userSituationPage = userVocAISituationMapper.selectPage(pageParam, userSituationWrapper);

        userSituationPage.getRecords().forEach(situation -> {
            LambdaQueryWrapper<UserVocAISituationOptionDO> optionWrapper = new LambdaQueryWrapper<>();
            optionWrapper.eq(UserVocAISituationOptionDO::getSituationId,situation.getId());
            List<UserVocAISituationOptionDO> options = userVocAISituationOptionMapper.selectList(optionWrapper);
            situation.setOptions(options);
        });
        return aiReadConverter.toUserVocAISituationPage(userSituationPage.getRecords(),userSituationPage.getTotal());

    }
}
